package com.feihua.starter.web.modules.hdb.mvc;

import com.feihua.framework.rest.ResponseJsonRender;
import com.feihua.framework.rest.interceptor.RepeatFormValidator;
import com.feihua.framework.rest.modules.common.mvc.BaseController;
import com.feihua.starter.service.api.ApiHdbArticlePoService;
import com.feihua.starter.service.api.ApiHdbNewsPoService;
import com.feihua.starter.service.modules.hdb.dto.HdbNewsDto;
import com.feihua.starter.service.modules.hdb.dto.SearchHdbNewsConditionDto;
import com.feihua.starter.service.modules.hdb.po.HdbNewsPo;
import com.feihua.utils.http.httpServletResponse.ResponseCode;
import feihua.jdbc.api.pojo.PageAndOrderbyParamDto;
import feihua.jdbc.api.pojo.PageResultDto;
import feihua.jdbc.api.utils.OrderbyUtils;
import feihua.jdbc.api.utils.PageUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 活动资讯管理
 * Created by revolver
 */
@RestController
@RequestMapping("/hdb")
public class HdbNewsController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(HdbNewsController.class);

    @Autowired
    private ApiHdbNewsPoService apiHdbNewsPoService;


    @Autowired
    private ApiHdbArticlePoService apiHdbArticlePoService;

    /**
     * 单资源，添加
     *
     * @param dto
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:news:add")
    @RequestMapping(value = "/news", method = RequestMethod.POST)
    public ResponseEntity add(@RequestBody HdbNewsDto dto) throws Exception {
        logger.info("添加活动资讯开始");
        logger.info("当前登录用户id:{}", getLoginUser().getId());
        ResponseJsonRender resultData = new ResponseJsonRender();
        dto.setCreateBy(getLoginUserId());
        HdbNewsDto r = apiHdbNewsPoService.addOrUpdate(dto);
        if (r == null) {
            // 添加失败
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            logger.info("code:{},msg:{}", resultData.getCode(), resultData.getMsg());
            logger.info("添加活动资讯结束，失败");
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        } else {
            // 添加成功，返回添加的数据
            resultData.setData(r);
            logger.info("添加活动资讯id:{}", r.getId());
            logger.info("添加活动资讯结束，成功");
            return new ResponseEntity(resultData, HttpStatus.CREATED);
        }
    }

    /**
     * 单资源，删除
     *
     * @param id
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:news:delete")
    @RequestMapping(value = "/news/{id}", method = RequestMethod.DELETE)
    public ResponseEntity delete(@PathVariable String id) {
        logger.info("删除活动资讯开始");
        logger.info("用户id:{}", getLoginUser().getId());
        logger.info("活动资讯id:{}", id);
        ResponseJsonRender resultData = new ResponseJsonRender();

        int r = apiHdbNewsPoService.deleteFlagByPrimaryKeyWithUpdateUser(id, getLoginUser().getId());
        if (r <= 0) {
            // 删除失败，可能没有找到资源
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            logger.info("code:{},msg:{}", resultData.getCode(), resultData.getMsg());
            logger.info("删除活动资讯结束，失败");
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        } else {
            // 删除成功
            logger.info("删除的活动资讯id:{}", id);
            logger.info("删除活动资讯结束，成功");
            return new ResponseEntity(resultData, HttpStatus.NO_CONTENT);
        }
    }


    /**
     * 单资源，删除
     *
     * @param id
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:news:article:delete")
    @RequestMapping(value = "/news/article/{id}", method = RequestMethod.DELETE)
    public ResponseEntity deleteArticle(@PathVariable String id) {
        logger.info("删除活动资讯开始");
        logger.info("用户id:{}", getLoginUser().getId());
        logger.info("活动资讯id:{}", id);
        ResponseJsonRender resultData = new ResponseJsonRender();

        int r = apiHdbArticlePoService.deleteFlagByPrimaryKeyWithUpdateUser(id, getLoginUser().getId());
        if (r <= 0) {
            // 删除失败，可能没有找到资源
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            logger.info("code:{},msg:{}", resultData.getCode(), resultData.getMsg());
            logger.info("删除活动资讯结束，失败");
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        } else {
            // 删除成功
            logger.info("删除的活动资讯id:{}", id);
            logger.info("删除活动资讯结束，成功");
            return new ResponseEntity(resultData, HttpStatus.NO_CONTENT);
        }
    }

    /**
     * 单资源，更新
     *
     * @param dto
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:news:update")
    @RequestMapping(value = "/news", method = RequestMethod.PUT)
    public ResponseEntity update(@RequestBody HdbNewsDto dto) throws Exception {
        logger.info("更新活动资讯开始");
        logger.info("当前登录用户id:{}", getLoginUser().getId());
        ResponseJsonRender resultData = new ResponseJsonRender();
        // 表单值设置
        dto.setUpdateBy(getLoginUserId());
        final HdbNewsDto hdbNewsDto = apiHdbNewsPoService.addOrUpdate(dto);

        if (hdbNewsDto == null) {
            // 更新失败，资源不存在
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            logger.info("code:{},msg:{}", resultData.getCode(), resultData.getMsg());
            logger.info("更新活动资讯结束，失败");
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        } else {
            // 更新成功，已被成功创建
            logger.info("更新活动资讯结束，成功");
            return new ResponseEntity(resultData, HttpStatus.CREATED);
        }
    }

    /**
     * 单资源，获取id活动资讯
     *
     * @param id
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:news:getById")
    @RequestMapping(value = "/news/{id}", method = RequestMethod.GET)
    public ResponseEntity getById(@PathVariable String id) {

        ResponseJsonRender resultData = new ResponseJsonRender();
        HdbNewsDto baseDataScopeDto = apiHdbNewsPoService.selectByPrimaryKey(id, false);
        if (baseDataScopeDto != null) {
            resultData.setData(baseDataScopeDto);
            return new ResponseEntity(resultData, HttpStatus.OK);
        } else {
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 复数资源，搜索活动资讯
     *
     * @param dto
     *
     * @return
     */
    @RepeatFormValidator
    @RequiresPermissions("hdb:news:search")
    @RequestMapping(value = "/newss", method = RequestMethod.GET)
    public ResponseEntity search(SearchHdbNewsConditionDto dto) {

        ResponseJsonRender resultData = new ResponseJsonRender();
        PageAndOrderbyParamDto pageAndOrderbyParamDto = new PageAndOrderbyParamDto(PageUtils.getPageFromThreadLocal(), OrderbyUtils.getOrderbyFromThreadLocal());
        // 设置当前登录用户id
        dto.setCurrentUserId(getLoginUser().getId());
        dto.setCurrentRoleId(getLoginUserRoleId());
        PageResultDto<HdbNewsDto> list = apiHdbNewsPoService.searchByMultiTable(dto, pageAndOrderbyParamDto);

        if (CollectionUtils.isNotEmpty(list.getData())) {
            resultData.setData(list.getData());
            resultData.setPage(list.getPage());
            return new ResponseEntity(resultData, HttpStatus.OK);
        } else {
            resultData.setCode(ResponseCode.E404_100001.getCode());
            resultData.setMsg(ResponseCode.E404_100001.getMsg());
            return new ResponseEntity(resultData, HttpStatus.NOT_FOUND);
        }
    }
}
